package com.hwadee.springboottwo.aop;

import com.hwadee.springboottwo.utils.VerifyUtil;
import com.hwadee.springboottwo.utils.result.DataResult;
import com.hwadee.springboottwo.utils.result.code.Code;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Component
@Aspect
public class AroundCut {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public static final String POINT_CUT = "execution(* com.hwadee.springboottwo.controller.StudentController.*(..)) || " +
            "execution(* com.hwadee.springboottwo.controller.GradeController.*(..))";



    @Around(AroundCut.POINT_CUT)
    public DataResult checkToken(ProceedingJoinPoint pjp) throws Throwable {
        //获取token
        String token = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("Token");
        System.out.println("Token: " + token);
        //验证
        String userInfoString = redisTemplate.opsForValue().get("Token::" + token);
        if(VerifyUtil.isNull(userInfoString)){//token失效
            return DataResult.errByErrCode(Code.LOGIN_OUT);
        }
        return (DataResult) pjp.proceed();

    }
}
